package edu.vt.ece3574.ninjatag;

/****************************************************************************
 * Copyright 2012 Landon Biggs, Chris Dusold, Brad Russell, and Craig Wertz	*
 * Licensed under the Apache License, Version 2.0 (the "License");			*
 * you may not use this file except in compliance with the License.			*
 * You may obtain a copy of the License at									*
 * 																			*
 * http://www.apache.org/licenses/LICENSE-2.0								*
 * 																			*
 * Unless required by applicable law or agreed to in writing, software		*
 * distributed under the License is distributed on an "AS IS" BASIS,		*
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.	*
 * See the License for the specific language governing permissions and		*
 * limitations under the License.											*
 ****************************************************************************/

import java.util.LinkedList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.BaseRequestListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Utility;

public class invite_screen extends Activity implements OnClickListener {
    private Handler mHandler;

    protected ListView friendsList;
    //protected static JSONArray jsonArray;
    protected FriendListAdapter adapter;
	
	private Button sendInvite, cancel, appInvite;
    ProgressDialog dialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.invites_screen);
        
        cancel = (Button)findViewById(R.id.backtoMatchmakingButton);
        sendInvite = (Button)findViewById(R.id.sendInvitesButton);
        appInvite = (Button)findViewById(R.id.inviteNewPlayers);
        
        cancel.setOnClickListener(this);
        sendInvite.setOnClickListener(this);
        appInvite.setOnClickListener(this);

        mHandler = new Handler();
        /*
        Bundle extras = getIntent().getExtras();
        String apiResponse = extras.getString("API_RESPONSE");
        try {
            jsonArray = new JSONArray(apiResponse);
        } catch (JSONException e) {
            showToast("Error: " + e.getMessage());
            return;
        }//*/
        friendsList = (ListView) findViewById(R.id.friends_list);
        friendsList.setItemsCanFocus(false);
        friendsList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        adapter = new FriendListAdapter(this);
        friendsList.setAdapter(adapter);
	}

	
	/*
	 *	The next couple methods are used to override the menu and back physical buttons on the phone.
	 *	onCreateOptionsMenu sets the menu to the custom 'main_menu'
	 *	onOptionsItemSelected starts an activity based on the selected option in the menu
	 * 	onBackPressed sends the app to the previous screen.
	 * 
	 */
	
    @Override
	public void onBackPressed(){
		Intent newIntent = new Intent(invite_screen.this, matchmaking_screen.class);
		startActivity(newIntent);
		return;
	}
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.main_menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	switch(item.getItemId() ){
    	
    	case R.id.menu_home:
    		Intent mainScreenIntent = new Intent(invite_screen.this, main_screen.class);
    		startActivity(mainScreenIntent);
    		finish();
    		break;
    		
    	
    	case R.id.menu_map:
    		Intent mapScreenIntent = new Intent(invite_screen.this, map_screen.class);
    		startActivity(mapScreenIntent);
    		finish();
    		break;
    		
    	case R.id.menu_settings:
    		Intent settingsScreenIntent = new Intent(invite_screen.this, settings_screen.class);
    		startActivity(settingsScreenIntent);
    		finish();
    		break;
    		
    	case R.id.menu_lock_or:
			
			if(getOrientation() == Configuration.ORIENTATION_PORTRAIT){
				this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				break;
			}
		
			else if(getOrientation() == Configuration.ORIENTATION_LANDSCAPE){
				this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				break;
			}
			else Toast.makeText(getBaseContext(), "Error: orientation was not locked", Toast.LENGTH_SHORT).show();
			break;
			
    	case R.id.menu_unlock_or:
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
			break;
    	}
    	return true;
    }
    
	@Override
	public void onClick(View v) {
		
		Intent invitesSentScreenIntent = new Intent(invite_screen.this, invites_sent_screen.class);
		Intent matchmakingScreenIntent = new Intent(invite_screen.this, matchmaking_screen.class);
		
		switch(v.getId()){
		
		case R.id.backtoMatchmakingButton:
			startActivity(matchmakingScreenIntent);
			finish();
			break;
			
		case R.id.sendInvitesButton:
			SparseBooleanArray checkedItems = adapter.getCheckedItemPositions(friendsList);
			if (checkedItems == null) {
				Log.e(this.getClass().getName(), "ListView returned null for checked items.");
			} else {
				final int checkedItemsCount = checkedItems.size();
				Log.d("Checked Items Size",String.valueOf(checkedItemsCount));
				for (int i = 0; i < checkedItemsCount; ++i) {
					// This tells us the item position we are looking at
					final int position = checkedItems.keyAt(i);
	
					// And this tells us the item status at the above position
					final boolean isChecked = checkedItems.valueAt(i);
	
					// And we can get our data from the adapter like that
					final PlayerIf currentItem = (PlayerIf) adapter.getItem(position);
					
					if (isChecked) {
						Log.d("Checkec", currentItem.getName());
					} else {
						Log.d("Uncheckec", currentItem.getName());
					}
				}
			}
			
			startActivity(invitesSentScreenIntent);
			finish();
			break;

		case R.id.inviteNewPlayers:
            dialog = ProgressDialog.show(invite_screen.this, "",
                    "Please wait...", true, true);
            String query = "select name, current_location, uid, pic_square from user where uid in (select uid2 from friend where uid1=me()) AND is_app_user != 1 order by name";
            Bundle params = new Bundle();
            params.putString("method", "fql.query");
            params.putString("query", query);
            Utility.mAsyncRunner.request(null, params,
                    new FriendsRequestListener());
			break;
		}
	}

	private void showToast(final String msg) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(invite_screen.this, msg, Toast.LENGTH_LONG);
                toast.show();
            }
        });
    }

    /**
     * Definition of the list adapter
     */
    public class FriendListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private LinkedList<String> keys;

        public FriendListAdapter(invite_screen friendsList) {
        	/*
            if (Utility.model == null) {
                Utility.model = new FriendsGetProfilePics();
            }
            Utility.model.setListener(this);//*/
        	keys = Utility.mFriends.getKeys();
            mInflater = LayoutInflater.from(friendsList.getBaseContext());
        }

        public SparseBooleanArray getCheckedItemPositions(ListView friendsList) {
        	SparseBooleanArray out = new SparseBooleanArray(friendsList.getCount());
        	for (int i=0;i<friendsList.getCount();i++){
        		out.append(i, ((ViewHolder)friendsList.getAdapter().getView(i, null, null).getTag()).checkBox.isChecked());
        	}
    		return out;
		}

		@Override
        public int getCount() {
            //return jsonArray.length();
        	return Utility.mFriends.getCount();
        }

        @Override
        public Object getItem(int position) {
        	/*
            JSONObject jsonObject = null;
            try {
                jsonObject = jsonArray.getJSONObject(position);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            return jsonObject;//*/
        	return Utility.mFriends.get(keys.get(position));
        }

        @Override
        public long getItemId(int position) {
            /*
        	try {
				return Long.valueOf(((JSONObject) getItem(position)).getString("uid"));
			} catch (NumberFormatException e) {
				Log.e("NumberFormatException",e.getMessage());
				e.printStackTrace();
			} catch (JSONException e) {
				Log.e("JSONException",e.getMessage());
				e.printStackTrace();
			}
            return 0;//*/
        	return Long.getLong(keys.get(position).substring(1));
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            PlayerIf player = Utility.mFriends.get(keys.get(position));
            View hView = convertView;
            if (convertView == null) {
                hView = mInflater.inflate(R.layout.friend_item, null, false);
                hView.setClickable(true);
                
                ViewHolder holder = new ViewHolder();
                holder.profile_pic = (ImageView) hView.findViewById(R.id.profile_pic);
                holder.name = (TextView) hView.findViewById(R.id.name);
                holder.info = (TextView) hView.findViewById(R.id.info);
                holder.checkBox = (CheckBox) hView.findViewById(R.id.checkBox1);
                hView.setTag(holder);
            }

            final ViewHolder holder = (ViewHolder) hView.getTag();
            //holder.profile_pic.setImageBitmap(player.getPicture()); //TODO: Fix.
            holder.name.setText(player.getName());
            if (player instanceof FacebookPlayer) {
                holder.info.setText(((FacebookPlayer)player).getLocation());
            } else {
                holder.info.setText("");
            }

            //holder.checkBox.setOnClickListener(holder.checkBox); //This was part of an example, I'm not sure if it's necessary
            hView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    holder.checkBox.toggle();
                }
            });
            
            return hView;
        }

    }

    class ViewHolder {
        ImageView profile_pic;
        TextView name;
        TextView info;
        CheckBox checkBox;
    }//*/

	/*
	 * callback after friends are fetched via me/friends or fql query.
	 */
	class FriendsRequestListener extends BaseRequestListener {
	
	    @Override
	    public void onComplete(final String response, final Object state) {
	        dialog.dismiss();
	        Intent myIntent = new Intent(getApplicationContext(), InviteNewPlayersScreen.class);
	        myIntent.putExtra("API_RESPONSE", response);
	        startActivity(myIntent);
	        finish();
	    }
	
	    public void onFacebookError(FacebookError error) {
	        dialog.dismiss();
	        Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(),
	                Toast.LENGTH_SHORT).show();
	    }
	}
    
    public int getOrientation()
 	{
 	    Display getOrient = getWindowManager().getDefaultDisplay();
 	    int orientation = Configuration.ORIENTATION_UNDEFINED;
 	    if(getOrient.getWidth()==getOrient.getHeight()){
 	        orientation = Configuration.ORIENTATION_SQUARE;
 	    } else{ 
 	        if(getOrient.getWidth() < getOrient.getHeight()){
 	            orientation = Configuration.ORIENTATION_PORTRAIT;
 	        }else { 
 	             orientation = Configuration.ORIENTATION_LANDSCAPE;
 	        }
 	    }
 	    return orientation;
 	}
}
